package cm.iccsoft.android.telecomcost.ui;

import java.util.ArrayList;

import cm.iccsoft.android.telecomcost.DatabaseManager;
import cm.iccsoft.android.telecomcost.R;
import cm.iccsoft.android.telecomcost.TelecomCost;
import cm.iccsoft.android.telecomcost.adapter.MonthlyThresholdAdapter;
import cm.iccsoft.android.telecomcost.entities.MonthlyThreshold;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;

public class MonthlyThresholdSpinner extends Spinner {
	
	private ArrayList<MonthlyThreshold> thresholds;
	private DatabaseManager db;
	private Context _context;
	private SpinnerAdapter _adapter;
	private int _position = 0;	

	@Override
	public void setSelection(int position) {
		Log.i("MonthlyThresholdSpinner", "setting selection..." + position);
		_position = position;
		super.setSelection(position);
	}

	public ArrayList<MonthlyThreshold> getThresholds()
	{
		return thresholds;
	}
	
	public MonthlyThreshold getSelectedThreshold() throws Exception
	{
		if(_adapter != null)
		{
			return (MonthlyThreshold) _adapter.getItem(_position);
		}
		
		throw new Exception("could not get selected MonthlyThreshold");
	}
	
	private void setList() throws Exception
	{
		if(_context != null)
		{			
			Log.i("MonthlyThresholdSpinner", "binding MonthlyThreshold...");
			thresholds = db.getMonthlyThreshold();	
			
			_adapter = new MonthlyThresholdAdapter(_context,
					android.R.layout.select_dialog_singlechoice, thresholds);
		}	
		else
		{
			throw new Exception("cannot set the adapter of the MonthlyThresholdSpinner...the context is null");
		}
	}	
	
	@Override
	public void setAdapter(SpinnerAdapter adapter) {
		Log.i("MonthlyThresholdSpinner", "setting the adapter...");
		try {
			setList();
		} catch (Exception e) {			
			e.printStackTrace();
		}		
		super.setAdapter(_adapter);			
	}

	@Override
	public SpinnerAdapter getAdapter() {		
		return _adapter;
	}

	public MonthlyThresholdSpinner(Context context) {
		super(context);
		_context = context;	
		db = TelecomCost.getDatabaseManager();
	}

	public MonthlyThresholdSpinner(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		_context = context;	
		db = TelecomCost.getDatabaseManager();
	}

	public MonthlyThresholdSpinner(Context context, AttributeSet attrs) {
		super(context, attrs);
		_context = context;		
		db = TelecomCost.getDatabaseManager();
	}	
}
